package twidledee.server;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import twidledee.client.Tweet;
import twidledee.client.TweetUpdateService;
import twidledee.client.User;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

@SuppressWarnings("serial")
public class TweetUpdateServiceImpl extends RemoteServiceServlet implements TweetUpdateService {

	private static final Logger LOG = Logger.getLogger(RegisterUserServiceImpl.class.getName());
	private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("transactions-optional");
	
	@Override
	public Tweet[] updateTweets() {
		List<Tweet> tweets = new ArrayList<Tweet>();
		PersistenceManager pm = getPersistenceManager();
		
		Query query = pm.newQuery(User.class);
		List<User> users = (List<User>) query.execute();
		for (int i=0; i<users.size(); i++){
			User u = users.get(i);
			Twitter twitter = new Twitter(u.getTwitterId(), u.getTwitterPassword());
			try{
				List<Status> userTweets = twitter.getHomeTimeline();
				for (int j=0; j<userTweets.size(); j++){
					Status s = userTweets.get(j);
					tweets.add(new Tweet(u, s.getCreatedAt(), s.getId(), s.getSource(), 
							s.getText(), s.hashCode(), s.isFavorited(), s.isRetweet()));
				}
			} catch (TwitterException e){
				//TODO
			}
		}
		return tweets.toArray(new Tweet[0]);
	}
	
	private PersistenceManager getPersistenceManager() {
	    return PMF.getPersistenceManager();
	}
	
}
